import cn from 'classnames';
import React from 'react';
import { Link } from 'react-router-dom';
import Label from '@/components/Label';
import { Loading, Form,Input,Button ,Message,Helper} from '@knownsec/react-component';
import s from './style.module.css';
import BreadCrumb from '@/components/BreadCrumb';
import recursionForm from '@/common/recursionForm';
import i from '../../../index.module.css';
import { getTokenTime,putTokenTime,getUserInfo,putUserInfo,modifyPwd } from '~/API';
function userEdit() {
  const [loading, setLoading] = React.useState(false);
  const [userInfo, setUserInfo] = React.useState(null);
  const form = React.useRef();
  const form2 = React.useRef();
  const form3 = React.useRef();
  const layout = {
    labelCol: { span: 8},
    wrapperCol: { span: 18 },
  };
  const validatormap = (rule, value, callback) => {
    const reg = new RegExp(
      '^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$'
    );
    const regPW = new RegExp('(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[^a-zA-Z0-9]).{8,16}')
    if (rule.field == 'real_name' && !value) {
      callback('真实姓名');
    } else if (rule.field == 'email' && !reg.test(value)) {
      callback('请填写邮件地址');
    } else if (rule.field == 'access_token_limit' && (isNaN(value)||value<10)) {
      callback('请填写超时时间(最小10分钟)');
    } else if (rule.field == 'max_retry_count' &&( isNaN(value)||value<1)) {
      callback('请填写最大错误登录次数');
    } else if (rule.field == 'max_multiple_devices' &&( isNaN(value)||value<1)) {
        callback('请填写设备登录数');
      } else if (rule.field == 'locked_time' && (isNaN(value)||value<1)) {
      callback('请填写错误登录锁定时间(分钟)');
    } else if (rule.field == 'password1' && !regPW.test(value)) {
      callback('须包含大小写字母、数字和特殊符号，8-16位');
    } else {
      return Promise.resolve();
    }
  };
  const onValues = (data) => {
    let values = recursionForm(data);
    form.current.setFieldsValue(values);
  };
  const onValues2 = (data) => {
    let values = recursionForm(data);
    form2.current.setFieldsValue(values);
  };
  const onValues3 = (data) => {
    let values = recursionForm(data);
    form3.current.setFieldsValue(values);
  };
  const sendForm =async (type) => {
    let putRes={}
    if(type===1){
      const res=await form.current.validateFields()
      putRes = await putUserInfo(res).catch(err =>{return err});
    }else if(type===2){
      const res=await form2.current.validateFields()
      const res_={}
      Object.entries(res).forEach(([key,val])=>{
        res_[key]=val*1;
      })
      putRes = await putTokenTime(res_).catch(err =>{return err});
    }else{
      const res=await form3.current.validateFields()
      putRes = await modifyPwd('POST',res).catch(err =>{return err});
    }
    if (putRes.status === 'success') {
      Message.show({
        pro: true,
        type: 'success',
        message: '修改成功',
        showClose: false,
      });
    }else{
      let msg = '';
      if (putRes.message) {
        msg = putRes.message;
      } else {
        msg = Object.values(putRes.data)[0];
      }
      Message.show({
        pro: true,
        type: 'error',
        message: msg,
        showClose: false,
      });
    }
    
  };

  React.useEffect(async() => {
    const user = await getUserInfo();
    setUserInfo(user.data)
    form.current.setFieldsValue(user.data);
    if(localStorage.group==='管理员'){
      const time = await getTokenTime();
      form2.current.setFieldsValue({ access_token_limit: time.data.access_token_limit,max_retry_count:time.data.max_retry_count,locked_time:time.data.locked_time,max_multiple_devices: time.data.max_multiple_devices });
    }
  }, []);
  return (
    <>
      <BreadCrumb
        arr={[
          { link: '', name: '用户管理' },
          { link: '', name: '账号设置', active: true },
        ]}
      />
      <div className={s.content}>
        <Loading show={loading} />
        <div className={s.content1}>
          <p className={s.wordMain_h} style={{ display:userInfo?.pw_timestamp>=Date()?'block':'none'}}>
            当前密码已有3个月未修改，请修改后再进行其他操作。
          </p>
          <Label className={s.labelDetail}>账号信息</Label>
          <div className={s.content1_2h}>
            <Form
              ref={form}
              {...layout}
              onValuesChange={(newItem, allValues) => {
                onValues(newItem, allValues);
              }}
            >
              <Form.Item name="real_name" label="真实姓名" rules={[{ required: true, validator: validatormap }]}>
                <Input pro className={cn(i.dib, i.w300)} placeholder={'请输入真实姓名'} autoComplete={'off'}/>
              </Form.Item>
              <Form.Item name="email" label="邮箱" rules={[{ required: true, validator: validatormap }]}>
                <Input pro className={cn(i.dib, i.w300)} placeholder={'请输入邮箱地址'} autoComplete={'off'}/>
              </Form.Item>
              <Form.Item name="phone" label="电话" className={s.telBox}>
                <Input pro className={cn(i.dib, i.w300)} placeholder={'请输入电话'} autoComplete={'off'}/>
              </Form.Item>
              <Form.Item name="department" label="所属部门"  className={s.telBox}>
                <Input pro className={cn(i.dib, i.w300)} placeholder={'请输入所属部门'} autoComplete={'off'}/>
              </Form.Item>
            </Form>
            <Button
              pro
              type="primary"
              onClick={() => {
                sendForm(1);
              }}
            >
          确定
            </Button>
          </div>
          {localStorage.group==='管理员'&&<>
            <Label className={s.labelDetail}>登录设置</Label>
            <div className={s.content1_2h}>
              <Form
                ref={form2}
                {...layout}
                onValuesChange={(newItem, allValues) => {
                  onValues2(newItem, allValues);
                }}
              >
                <div className={s.itemBox}> <Form.Item name="max_retry_count" label="最大错误登录次数" rules={[{ required: true, validator: validatormap }]}>
                  <Input pro className={cn(i.dib, i.w300)} placeholder={'请输入1-5之间的数字'} autoComplete={'off'}/>
                </Form.Item>
                <span className={s.span}>次<Helper
                  placement="top"
                  overlay={'设置用户连续错误登录的最大次数，超过最大次数，将锁定该用户帐号'}
                  className={s.helper}
                ></Helper></span>
                </div>
                <div className={s.itemBox}><Form.Item name="locked_time" label="错误登录锁定时间" rules={[{ required: true, validator: validatormap }]}>
                  <Input pro className={cn(i.dib, i.w300)} placeholder={'请输入时间（1-20分钟）'} autoComplete={'off'}/>
                </Form.Item>
                <span className={cn(s.span, s.pr)}>分钟<Helper
                  placement="top"
                  overlay={'设定用户账号锁定后，多少时间后解锁'}
                  className={s.helper}
                ></Helper></span>
                </div>
                <div className={s.itemBox}><Form.Item name="access_token_limit" label="会话超时设置" rules={[{ required: true, validator: validatormap }]}>
                  <Input pro className={cn(i.dib, i.w300)} placeholder={'请输入时间（10-120分钟）'} autoComplete={'off'}/>
                </Form.Item>
                <span className={s.span}>分钟<Helper
                  placement="top"
                  overlay={'设定用户多少时间没有使用系統后需要重新登录'}
                  className={s.helper}
                ></Helper></span>
                </div>
                <div className={s.itemBox}><Form.Item name="max_multiple_devices" label="多端登录" rules={[{ required: true, validator: validatormap }]}>
                  <Input pro className={cn(i.dib, i.w300)} placeholder={'请输入设备数'} autoComplete={'off'}/>
                </Form.Item>
                <span className={s.span}>个<Helper
                  placement="top"
                  overlay={'设定同一用户在同一时间最大允许多少个终端登录'}
                  className={s.helper}
                ></Helper></span>
                </div>
              </Form>
              <Button
                pro
                type="primary"
                onClick={() => {
                  sendForm(2);
                }}
              >
          确定
              </Button>
            </div>
          </>}
    
          
          <Label className={s.labelDetail}>密码修改
          {/* <Helper
            placement="top"
            overlay={'累计3个月未更改密码，系统将強制修改密码，请及时修改'}
            className={s.helper}
          ></Helper> */}
          </Label>
          <div className={s.content1_2h}>
            <Form
              ref={form3}
              {...layout}
              onValuesChange={(newItem, allValues) => {
                onValues3(newItem, allValues);
              }}
            >
              {/* type="password" */}
              <Form.Item name="old_password" label="原密码" rules={[{ required: true, validator: validatormap }]}>
                <Input pro className={cn(i.dib, i.w300)} type="password" placeholder={'请输入原密码'} autoComplete={'off'}/>
              </Form.Item>
              <div className={s.itemBox}>
                <Form.Item name="password1" label="新密码" rules={[{ required: true, validator: validatormap }]}>
                  <Input pro className={cn(i.dib, i.w300)} type="password" placeholder={'请输入新密码'} autoComplete={'off'}/>
                </Form.Item>
                <Helper
                  placement="top"
                  overlay={'密码必须包含大小写字母、数字和特殊符号，长度为8-16位'}
                  className={cn(s.helper,s.helper2)}
                ></Helper>
              </div>
              <Form.Item name="password2" label="确认密码" rules={[{ required: true, validator: validatormap }]}>
                <Input pro className={cn(i.dib, i.w300)} type="password" placeholder={'请再次输入新密码'} autoComplete={'off'}/>
              </Form.Item>
            </Form>
            <Button
              pro
              type="primary"
              onClick={() => {
                sendForm(3);
              }}
            >
          确定
            </Button>
          </div>
        </div>
      </div>
    </>
  );
}

export default userEdit;
